
import os
import json
from loguru import logger
from mem0 import MemoryClient

def load_settings():
    """Loads settings from settings.txt."""
    settings_path = os.path.join(os.path.dirname(__file__), '..', 'settings.txt')
    try:
        with open(settings_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        logger.error(f"Failed to load settings: {e}")
        return {}

def run_simple_mem0_test():
    """
    A simple, isolated test for mem0 functionality.
    """
    logger.info("--- Starting Simple mem0 Test ---")
    
    settings = load_settings()
    api_key = settings.get("MEM0_API_KEY")
    
    if not api_key:
        logger.error("MEM0_API_KEY not found in settings.txt. Test cannot proceed.")
        return

    try:
        mem0 = MemoryClient(api_key=api_key)
        logger.info("MemoryClient initialized successfully.")
    except Exception as e:
        logger.error(f"Failed to initialize MemoryClient: {e}")
        return

    user_id = "simple-test-user-123"
    test_fact = "我的名字叫小映"
    test_query = "我叫什么名字？"

    # 1. Add memory
    try:
        add_result = mem0.add([{"role": "user", "content": test_fact}], user_id=user_id)
        logger.info(f"Called mem0.add() with: '{test_fact}'")
        logger.info(f"mem0.add() returned: {add_result}")
    except Exception as e:
        logger.error(f"An error occurred during mem0.add(): {e}")
        return

    # 2. Search memory
    try:
        search_results = mem0.search(query=test_query, user_id=user_id)
        logger.info(f"Called mem0.search() with query: '{test_query}'")
        logger.info(f"mem0.search() returned: {search_results}")
    except Exception as e:
        logger.error(f"An error occurred during mem0.search(): {e}")
        return

    # 3. Verify result
    if search_results and isinstance(search_results, list) and len(search_results) > 0:
        memory_text = search_results[0].get('memory')
        if memory_text and "小映" in memory_text:
            logger.success("--- Simple mem0 Test PASSED! ---")
            print(f"SUCCESS: Agent correctly recalled the name. Full response: {search_results}")
        else:
            logger.error("--- Simple mem0 Test FAILED: Name not found in memory. ---")
            print(f"FAILURE: Agent did not recall the name. Full response: {search_results}")
    else:
        logger.error("--- Simple mem0 Test FAILED: No results returned from search. ---")
        print(f"FAILURE: No results from search. Full response: {search_results}")

if __name__ == "__main__":
    run_simple_mem0_test()
